<template>
  <a-drawer
    :width="350"
    :visible="drawerVisible"
    title="修改部门"
    @close="onDrawerClose"
    :wrapStyle="{ height: 'calc(100% - 108px)', overflow: 'auto', paddingBottom: '108px' }"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" layout="vertical">
        <!-- name -->
        <a-form-item label="部门名称" :wrapperCol="wrapperCol">
          <a-input v-decorator="['name', { rules: [{ required: true, message: '请填写部门名称' }] }]" />
        </a-form-item>
        <!-- pid -->
        <a-form-item label="上级部门" :wrapperCol="wrapperCol">
          <a-tree-select
            v-decorator="['pid', { rules: [{ required: true }], initialValue: '0' }]"
            showSearch
            :treeData="treeDeptList"
            :treeDataSimpleMode="treeDataSimpleMode"
            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="选择菜单作为上级菜单"
            treeNodeFilterProp="title"
            @change="handleTreeSelectChange"
          />
        </a-form-item>
        <!-- sort -->
        <a-form-item label="排序" :wrapperCol="wrapperCol">
          <a-input-number v-decorator="['sort', { initialValue: 0 }]" :precision="0" :min="0" :max="99999" />
        </a-form-item>
      </a-form>
    </a-spin>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <a-button :style="{ marginRight: '8px' }" @click="onDrawerClose">{{ $t('cancel') }}</a-button>
      <a-button :loading="confirmLoading" @click="onDrawerConfirm" type="primary">{{ $t('confirm') }}</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { getDeptList, saveDept } from '@/api/auth'
import pick from 'lodash.pick'

const formFields = ['name', 'pid', 'sort']

export default {
  name: 'DeptFormModal',
  data() {
    return {
      id: '',
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      form: this.$form.createForm(this),
      treeDeptList: [],
      treeDataSimpleMode: { id: 'id', pId: 'pid', rootPId: '-1' },
      drawerVisible: false,
      confirmLoading: false
    }
  },
  methods: {
    add() {
      this.drawerVisible = true
      this.getMenuList()
      this.$nextTick(() => {
        this.form.setFieldsValue()
      })
    },
    edit(record) {
      this.drawerVisible = true
      this.getMenuList()
      console.log(record)
      this.id = record.id
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, formFields))
      })
    },
    onDrawerClose() {
      this.drawerVisible = false
    },
    onDrawerConfirm() {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        values.id = this.id
        console.log('errors:', errors, 'val:', values)
        console.log('commit icon:', values.icon)
        if (!errors) {
          console.log('values:', values)
          saveDept(values).then(res => {
            console.log(res.code === 0)
            if (res.code === 0) {
              this.drawerVisible = false
              this.confirmLoading = false
              this.$emit('ok')
            }
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleTreeSelectChange(value, node, extra) {
      console.log(this.form.getFieldsValue(['pid']))
      console.log(value)
    },
    getMenuList() {
      getDeptList().then(res => {
        const childrenList = []
        const rootMenu = {
          id: '0',
          pid: '-1',
          name: '顶级部门',
          value: '0',
          children: []
        }
        console.log('res.data', res.data)
        res.data.push(rootMenu)
        this.listToTreeSelectData(res.data, childrenList, '-1')
        console.log('childrenList', childrenList)
        this.treeDeptList = childrenList
      })
    },
    listToTreeSelectData(list, tree, rootPid) {
      list.forEach(item => {
        const { id, pid, name } = item
        // 判断是否为父级菜单
        if (pid === rootPid) {
          const child = {
            id,
            pid,
            title: name,
            value: id,
            children: []
          }
          // 迭代 list， 找到当前菜单相符合的所有子菜单
          this.listToTreeSelectData(list, child.children, id)
          // 删掉不存在 children 值的属性
          if (child.children.length <= 0) {
            delete child.children
          }
          // 加入到树中
          tree.push(child)
        }
      })
    }
  }
}
</script>

<style scoped></style>
